﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.BackgroundAudio;
using System.Windows.Threading;
using System.Threading;
using GestureEventArgs = System.Windows.Input.GestureEventArgs;
using Microsoft.Phone.Shell;
using Microsoft.Xna.Framework.Media;

namespace VoiceRepeater
{
    public partial class MainPage : PhoneApplicationPage
    {
        private bool isRepeating = false;

        private MediaElement mediaPlayer;
        private DispatcherTimer currentPos;

        private TimeSpan startTime;
        private TimeSpan endTime;

        private List<VoiceSection> sectionList;

        /// <summary>
        /// Timer for voice repeating
        /// </summary>
        private DispatcherTimer repeatTimer;

        private PlayListPage listPage;

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            mediaPlayer = new MediaElement();
            currentPos = new DispatcherTimer();
            //Bar timer Event
            currentPos.Tick += new EventHandler(currentPos_Tick);

            LayoutRoot.Children.Add(mediaPlayer);

            mediaPlayer.AutoPlay = false;
            mediaPlayer.Source = new Uri("test.mp3", UriKind.Relative);
            mediaPlayer.Position = new TimeSpan(0);
            mediaPlayer.BufferingProgressChanged += new RoutedEventHandler(mediaPlayer_BufferingProgressChanged);
            mediaPlayer.MediaOpened +=  new RoutedEventHandler(mediaPlayer_Opened);
            mediaPlayer.MediaEnded += new RoutedEventHandler(mediaPlayer_MediaEnded);

            repeatTimer = new DispatcherTimer();
            repeatTimer.Tick += OnTimerTick;

            sectionList = new List<VoiceSection>();

            btnA.IsEnabled = false;
            btnB.IsEnabled = false;

            listPage = new PlayListPage();
        }

        /*Set progressBar2*/
        void currentPos_Tick(object sender, EventArgs e)
        {
            progressBar2.Value = (int)mediaPlayer.Position.TotalMilliseconds;
        }

        /*When media be opened*/
        void mediaPlayer_Opened(object sender, EventArgs e)
        {
            bool hasTimeSpan = mediaPlayer.NaturalDuration.HasTimeSpan;
            if (false == hasTimeSpan)
            {
                progressBar2.Maximum = 100;
            }
            else
            {
                progressBar2.Maximum = mediaPlayer.NaturalDuration.TimeSpan.TotalMilliseconds;
            }
        }

        void mediaPlayer_MediaEnded(object sender, EventArgs e)
        {
            mediaPlayer.Stop();
            mediaPlayer.Position = new TimeSpan(0);
            btnPlay.Content = "Play";
        }


        public void mediaPlayer_BufferingProgressChanged(object sender, RoutedEventArgs e)
    {
    }

        private void OnTimerTick(Object sender, EventArgs args)
        {
            mediaPlayer.Pause();
            Thread.Sleep(1000);
            mediaPlayer.Position = startTime;
            mediaPlayer.Play();
        }

        private void btnA_Click(object sender, RoutedEventArgs e)
        {
            // TODO: Record time of point A
            startTime = mediaPlayer.Position;

            btnB.IsEnabled = true;
        }

        private void btnB_Click(object sender, RoutedEventArgs e)
        {
            // TODO: Record time of point B
            endTime = mediaPlayer.Position;

            

        }

        private void btnPlay_Click(object sender, RoutedEventArgs e)
        {
            if (btnPlay.Content.ToString() == "Play")
            {
                btnPlay.Content = "Pause";                
                mediaPlayer.Play();
                btnA.IsEnabled = true;
                currentPos.Start();
            }
            else if (btnPlay.Content.ToString() == "Pause")
            {
                btnPlay.Content = "Play";
                mediaPlayer.Pause();
                currentPos.Stop(); ;
            }
            else
            {
                repeatTimer.Stop();
                btnPlay.Content = "Pause";
                listBoxSections.SelectedIndex = -1;
                mediaPlayer.Pause();
                mediaPlayer.Position = endTime;
                mediaPlayer.Play();

                btnA.IsEnabled = true;
            }
        }

        /// <summary>
        /// Event handler for repeat button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRepeat_Click(object sender, RoutedEventArgs e)
        {    

            if (startTime != null)
            {
                string formatstr = @"hh\:mm\:ss\.ff";                
                listBoxSections.Items.Add(string.Format("{0} --> {1}", startTime.ToString(formatstr), endTime.ToString(formatstr)));

                sectionList.Add(new VoiceSection(startTime, endTime));

                btnA.IsEnabled = false;
                btnB.IsEnabled = false;
                StartRepeat();
            }
        }

        /// <summary>
        /// Start repeat with the selected start and end point
        /// </summary>
        private void StartRepeat()
        {
            btnPlay.Content = "Resume";
            isRepeating = true;
            mediaPlayer.Pause();
            mediaPlayer.Position = startTime;
            repeatTimer.Interval = endTime - startTime;
            repeatTimer.Start();
            mediaPlayer.Play();
        }

        /// <summary>
        /// Change repeat section
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listBoxSections_DoubleTap(object sender, GestureEventArgs e)
        {
            int index = listBoxSections.SelectedIndex;

            startTime = sectionList[index].Start;
            endTime = sectionList[index].End;

            StartRepeat();
        }

        private void btnShowList_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/PlayListPage.xaml", UriKind.Relative));
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (PhoneApplicationService.Current.State.ContainsKey("currentSong"))
            {
                Song currentSong = PhoneApplicationService.Current.State["currentSong"] as Song;
                //mediaPlayer.Source = currentSong.;
            }
        }
    }
}